from zhipuai import ZhipuAI
import time
class TranslationRobot:
    def __init__(self, api_key):
        self.client = ZhipuAI(api_key="78a5edea9596183887ccf21c33ad7aed.X8rYa9YXlKRdCqNY")
    def translation_Robot(self, header_content, source_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                        {"role": "user", "content": "作为一个C转rust的专家，在保持变量名称和函数名称一致，实现从C到Rust的迁移,尽量使用rust的风格，并且保证代码的安全性"},
                        {"role": "assistant", "content": "当然，我会保持变量名称和函数名称的一致，请告诉我你要转换的代码"},
                        {"role": "user", "content": f"我要转换的c源代码是{source_content}头文件是：{header_content}，请只给我转换的rust代码不需要输出其他信息"}
                    ],
                    max_tokens=4096,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None

    def compiler_error_fixer(self, error_content, source_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    
                    messages=[
                        {"role": "user", "content": "As a Rust expert, are you able to correct and fix the code based on compilation errors to make it pass Rusts compilation"}, 
                            {"role": "assistant", "content": "Certainly, I will correct and fix the code based on the source code and compilation errors to make it pass Rust’s compilation."}, 
                            {"role": "user", "content": f"The compilation error message is: {error_content}, and the Rust source code is {source_content}. Please help me fix the Rust code based on the error message without outputting any additional information. Do not change the function names. Please output the complete code."} 
                                                                                                                                                                                                     ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None
    def code_optimization_fixer(self, source_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                        {"role": "user", "content": "作为一个rust代码优化专家，你能够将C风格，内存和线程不安全的rust代码改为内存，线程安全的rust风格的rust代码"},
                        {"role": "assistant", "content": "当然，我会对C风格，内存和线程不安全的rust代码改为内存，线程安全的rust风格的rust代码"},
                        {"role": "user", "content": f"我要转换的rust源代码是{source_content},请只给我修复的rust代码不需要输出其他信息，不要更改函数的名称"}
                    ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None  
    
    def code_alasy(self, code_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                
                        {"role": "user", "content": f"Please understand the functional intent and function intent of this class, and output the related English pseudo-code. The code of this class is as follows: {code_content}"}

                    ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None

    def code_Rust_syntax_fixer(self, code_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                
                        {"role": "user", "content": f"You are an expert in Rust syntax; please identify if the code syntax is correct according to Rust syntax. If any irregularities are found, fix them. For instance, if there are places that should be commented but are not, if modules are not correctly imported, if unsafe code is used, or if parentheses are not aligned, correct these issues. Maintain the integrity of the code, and then wrap the code in ``````.: the source code is{code_content}"}

                    ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None
    
    def code_translate(self, code_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数
        rust_language_features = """
Rust is a system programming language that emphasizes safety and concurrency, and its style is mainly reflected in the following aspects:

Ownership:
- Each piece of data in Rust can only have one owner.
- The owner is responsible for managing the lifecycle of the data.

Borrowing:
- Data can be borrowed through immutable references (&T) or mutable references (&mut T).
- Immutable references allow multiple read operations but do not allow modification.
- Mutable references allow modification of the data, but only one mutable reference can exist at a time.

Lifetimes:
- Rust uses lifetimes to ensure that references are always valid.
- Lifetimes are not about the duration but about the scope in which the reference remains valid.

Rust controls memory in the following ways:

Ownership System:
- When a variable goes out of scope, Rust automatically calls the drop function to clean up memory.
- This avoids the need for manual memory management and reduces the risk of memory leaks.

Borrow Checking:
- The Rust compiler checks the validity of references during compilation, which is called borrow checking.
- Borrowing rules prevent data races.

Stack and Heap Allocation:
- Rust uses the stack to store small, fixed-size data.
- For dynamically sized or long-lived data, Rust uses heap allocation.
- The Box<T> type in Rust is a pointer that allocates memory on the heap.

Smart Pointers:
- Rust provides various smart pointers, such as Box<T>, Rc<T>, Arc<T>, RefCell<T>, and Mutex<T>.
- These smart pointers offer different memory management strategies, such as reference counting (Rc<T> and Arc<T>) or dynamic borrow checking (RefCell<T>).

Pattern Matching:
- Rust's pattern matching can safely destructure and access data structures.
- In pattern matching, Rust ensures that all possible cases are handled, which helps prevent memory leaks.

Zero-Cost Abstractions:
- Rust's abstractions do not introduce additional runtime overhead.
- This means programmers can use high-level abstractions without sacrificing performance.
"""
        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                    {"role": "user", "content": f"As a Rust code optimization expert, you are familiar with and understand the relevant Rust styles, such as {rust_language_features}"},
                    {"role": "assistant", "content": "Of course, I am very familiar with the above styles and understand their pros and cons."},
                    {"role": "user", "content": f"You are now a native Rust library expert, you are familiar with Rust style and API, please output the corresponding Rust code based on the class's functional intent and function intent, if you encounter C language style, try to convert it to Rust language style, you need to fully implement all the functions of the class, you cannot omit, the intent of the Rust class is as follows: {code_content},The code needs to be wrapped in ``````"}
                ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None
    
    def fix_function(self, function_content,error_info):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                
                       {
  "role": "user",
  "content": f"Please fix the code based on the error message. The error message is {error_info}, and the code is {function_content}. Only provide me with the fixed Rust function code, no other information is needed. If there are additional inputs, remember to retain them and do not change the function's name."
}
                    ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None
    
    def fix_function_unexpected_closing_delimiter(self, function_content,error_info):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                
                       {
  "role": "user",
  "content": f"I need to make the closing delimiters match successfully; it’s possible that there is one too many closing delimiters or one too few. You need to find the error in the code, which is {function_content}, and then fix it. Only provide the corrected Rust code, no other information is needed."
}
                    ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None
    

    def fix_line_function(self, code_content,line,error_info):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                    model="glm-4-air",  # 请填写您要调用的模型名称
                    messages=[
                
                        {"role": "user", "content": f"请为我提供rust函数转换成rust风格代码并且优化修复错误，根据错误信息修复函数，错误信息是{error_info},函数是{code_content},请只给我修复的rust函数代码不需要输出其他信息，不要更改函数的名称"}
                    ],
                    top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None

    def code_Evaluater(self, source_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                model="glm-4-air",  # 请填写您要调用的模型名称
                messages = [{ "role": "user","content": f"分析并评估以下rust代码片段{source_content}的质量和功能。在生成你的回答之前，请先生成推荐示例代码，然后对代码进行评分。输出一个总分"}],
                top_p= 0.7,
    temperature= 0.9,
    max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None  
     

    def find_function_lack_of_src(self, left_content, right_content):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                model="glm-4-air",  # 请填写您要调用的模型名称
                messages = [{ "role": "user","content": f"你现在是函数名字分析师，你会审视两段函数名字列表，然后根据函数功能意图分辨左边的函数名字列表，对比右边的函数列表缺少了哪些函数功能，然后你只需要说出右边缺少的函数功能对应的函数名字，并且以数组的形式输出,这是坐标的函数列表{left_content}，这是右边的函数列表{right_content}"}],
                top_p= 0.7,
                temperature= 0.9,
                max_tokens=4095,
                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None  
    
    def fix_lack_of_code(self, source_content,lack_list):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
    model="glm-4-air",  # Please fill in the model name you want to call
    top_p=0.7,
    temperature=0.9,
    max_tokens=4095,
    messages=[
        {
            "role": "user",
            "content": f"Based on the missing functions {lack_list} and the current code {source_content}, supplement the missing code according to the current code context, and then provide the complete code. The code needs to be wrapped in ``````."
        }
    ]
)
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None  
    
    def fix_code_by_python(self, error_content,file_path):
        max_retries = 3  # 设置最大重试次数
        retries = 0  # 初始化重试次数

        while retries < max_retries:
            try:
                response = self.client.chat.completions.create(
                model="glm-4-air",  # 请填写您要调用的模型名称
                top_p= 0.7,
                temperature= 0.9,
                max_tokens=4095,
               messages = [{"role": "user", "content": f"You are now a Rust syntax repair machine. You can use Python instructions to fix Rust syntax errors. First, you need to analyze the solution for Rust errors, then generate Python code that can fix the errors based on the solution. For example, if you encounter a file UTF8 error, delete the text that is not UTF8 in the code. If you encounter a misaligned parenthesis error, delete the incorrect parenthesis. The error message is {error_content} and the file path is {file_path}. Please provide Python code that can fix the Rust error. The code needs to be wrapped in ``````."}]

                )
                #print(response.choices[0].message)
                return response.choices[0].message.content
            except Exception as e:
                print(f"网络错误: {e}, 正在重试...")
                retries += 1
                time.sleep(60*(retries+1))  # 等待1分钟

        print("达到最大重试次数，放弃操作。")
        return None